package com.aviccxzx.smarthome;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.aviccxzx.smarthome.base.BaseActivity;
import com.aviccxzx.smarthome.base.IHandlerLikeNotify;
import com.aviccxzx.smarthome.bug.CrashHandler;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.update.BaseAndroid;
import com.aviccxzx.smarthome.update.BaseConfig;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.xiaowei.core.CoreApplication;

import org.xutils.x;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

import cn.jpush.android.api.JPushInterface;

public class GosApplication extends CoreApplication implements IHandlerLikeNotify{

    public static int flag = 0;

    public static final String SDCARD_CACHE_DIR = Environment.getExternalStorageDirectory() + "/smarthome";
    public List<Activity> unDestroyActivityList = new ArrayList<Activity>();

    public List<Activity> activityList = new LinkedList<Activity>();

    public static GosApplication instance;
    public static String GMac = "";
    public static AMapLocationClient locationClient = null;
    private String TAG = "GosApplication";

    private IHandlerLikeNotify currentNotify;
    private Stack<BaseActivity> activityStack;

    public void onCreate() {
        super.onCreate();
        App.setApp(this);
        instance = this;
//        initImageLoader(this, null);
        GizWifiSDK.sharedInstance().startWithAppID(this, MsgID.APPID);
        JPushInterface.setDebugMode(true); 	// 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);     		// 初始化 JPush

        //摄像头相关
        activityStack = new Stack<>();
        currentNotify = null;

        x.Ext.init(this);
        x.Ext.setDebug(true);

        //收集日志
        CrashHandler mCrashHandler = CrashHandler.getInstance();
        mCrashHandler.setCustomCrashHanler(getApplicationContext());

        BaseAndroid.init(new BaseConfig()
                .setAppColor(R.color.colorPrimary)//app主调颜色，用于标题栏等背景颜色
                .setAppLogo(R.mipmap.ic_launcher)//app图标
                .setFailPicture(R.mipmap.ic_launcher)//加载加载失败和加载中显示的图
                .setLoadingView(R.mipmap.launcher_icon)//设置加载框的gif图
                .setCode(0)//网络请求成功返回的code数字，默认为1
                .setHttpCode("code")//网络请求返回的code字段名称，默认为code
                .setHttpMessage("message")//网络请求返回的message字段名称，默认为message
                .setHttpResult("response"));//网络请求返回的result字段名称，默认为result

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base); MultiDex.install(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        System.exit(0);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 修改当前显示的 Activity 引用
     *
     * @param currentNotify
     */
    public void setCurrentNotify(IHandlerLikeNotify currentNotify) {
        this.currentNotify = currentNotify;
    }

    public IHandlerLikeNotify getCurrentNotify() {
        return currentNotify;
    }

    @Override
    public void onNotify(int what, int arg1, int arg2, Object obj) {

    }

    /**
     * 底层所有的回调接口
     *
     * @param what
     * @param uchType
     * @param channel
     * @param obj
     */
    public synchronized void onJniNotify(int what, int uchType, int channel, Object obj) {
        if (null != currentNotify) {
            currentNotify.onNotify(what, uchType, channel, obj);
        } else {
            Log.e(TAG, "currentNotify is null!");
        }
    }

    /**
     * activity 入栈
     *
     * @param activity
     */
    public void push(BaseActivity activity) {
        activityStack.push(activity);
    }

    /**
     * activity 出栈
     */
    public BaseActivity pop() {
        return (false == activityStack.isEmpty()) ? activityStack.pop() : null;

    }

    /**
     * 初始化图片加载器
     *
     * @param mContext
     * @param defaultOptions
     */
    /*public static void initImageLoader(Context mContext,
                                       DisplayImageOptions defaultOptions) {

        if (defaultOptions == null)
            defaultOptions = buildImageOptions(mContext);
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                mContext)
                .threadPoolSize(5)//线程池内加载的数量
                .defaultDisplayImageOptions(defaultOptions)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .memoryCache(new WeakMemoryCache())
                .memoryCacheSize(30 * 1024 * 1024)
                .discCache(
                        new UnlimitedDiscCache(new File(SDCARD_CACHE_DIR + "/imagecache")))
                .build();
        ImageLoader.getInstance().init(config);
    }*/


    private Toast toast;

    /**
     * 短时间显示Toast 作用:不重复弹出Toast,如果当前有toast正在显示，则先取消
     *
     * @param info 显示的内容
     */
    public void showToast(String info) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(this, info, Toast.LENGTH_SHORT);
        toast.setText(info);
        toast.show();
    }

    /**
     * 退出应用
     */
    public void quit() {
        for (Activity activity : unDestroyActivityList) {
            if (null != activity) {
                activity.finish();
            }
        }
        unDestroyActivityList.clear();
    }

    /**
     * 局部退出 去掉局部集合里的单个页面
     *
     * @param activityname
     */
    public void RemoveActivity(String activityname) {
        if (null != activityList && activityList.size() > 0) {
            for (Activity activity : activityList) {
                if (activity.getClass().getCanonicalName().equals(activityname)
                        && (activity != null && !activity.isFinishing())) {
                    activityList.remove(activity);
                }
            }
        }
    }

    public static GosApplication getInstance() {
        return instance;
    }
}
